package com.dataaccess.dataaccess.web.service;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.dataaccess.dataaccess.common.base.BaseService;
import com.dataaccess.dataaccess.common.utils.Dict;
import com.dataaccess.dataaccess.common.utils.appkit.ConfigKit;
import com.dataaccess.dataaccess.common.utils.appkit.FirefightingiotKit;
import com.dataaccess.dataaccess.model.*;
import com.dataaccess.dataaccess.support.aibox.PictureDownload;
import com.dataaccess.dataaccess.support.model.RespEntity;
import com.dataaccess.dataaccess.support.mybatisplus.QueryWrapper;
import com.dataaccess.dataaccess.support.utils.DateUtils;
import com.dataaccess.dataaccess.support.utils.MyLogger;
import com.dataaccess.dataaccess.support.utils.requestutil.HttpRequestUtil;
import com.dataaccess.dataaccess.web.mapper.*;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;


/**
 * @author Yang
 */
@Service
@Slf4j
public class VisualizationVideoAlarmService extends BaseService {
    @Resource
    public MyLogger logger;
    @Resource
    private VideoAlarmDeviceDataChangedMapper videoAlarmDeviceDataChangedMapper;
    @Resource
    private VideoNormalDeviceDataChangedMapper videoNormalDeviceDataChangedMapper;
    @Resource
    private UploadService uploadService;
    @Resource
    AlarmRecordMapper alarmRecordMapper;
    @Resource
    private AlarmAllDeviceDataChangedMapper alarmAllDeviceDataChangedMapper;
    @Resource
    private CameraAlarmDeviceDataChangedMapper cameraAlarmDeviceDataChangedMapper;
    @Resource
    private AsyncService asyncService;
    @Resource
    private HikEventMapper hikEventMapper;

    /**
     * 接受视频报警信息
     *
     * @param jsonParam
     * @return
     */
    public JSONObject VisualizationInfo(HttpServletRequest request, Dict jsonParam) throws Exception {
        JSONObject jsonParam1 = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        logger.info("智瓴报警---------" + jsonParam1);
        String content = jsonParam1.getStr("text");
        String time = jsonParam1.getStr("dateTime");
        String add = jsonParam1.getStr("addr");

        JSONObject jsonParamN = new JSONObject();

        //应用平台的设备号
        jsonParamN.put("number", jsonParam1.getStr("devId"));
        String fireAlarmTypeName = "";
        String fireCode = "";
        //校验报警类型
        String alarmTypeName = "";
        if ("0".equals(jsonParam1.getStr("type"))) {
            alarmTypeName = "人群惊扰报警";
            fireAlarmTypeName = "实时画面";
            fireCode = "6001";
        }
        if ("1".equals(jsonParam1.getStr("type"))) {

            alarmTypeName = "火灾烟雾报警";
            fireAlarmTypeName = "烟感报警";
            fireCode = "6003";
        }
        if ("2".equals(jsonParam1.getStr("type"))) {

            alarmTypeName = "消防通道报警";
            fireAlarmTypeName = "消防通道堵塞";
            fireCode = "6006";
        }
        if ("3".equals(jsonParam1.getStr("type"))) {

            alarmTypeName = "岗位监测报警";
            fireAlarmTypeName = "人员离岗";
            fireCode = "6002";
        }
        //上传文件到服务器
        String picPath = "";
        String picName = "";
        String videoPath = "";
        String videoName = "";
        Object object = uploadService.uploadFile(jsonParam, request);
        if (object instanceof List) {
            List<Map<String, Object>> fileList = (ArrayList) object;
            for (Map<String, Object> fileMap : fileList) {
                if (fileMap.get("filePath").toString().endsWith(".mp4")) {
                    videoPath = fileMap.get("filePath").toString();
                    videoName = fileMap.get("fileName").toString();
                } else {
                    picPath = fileMap.get("filePath").toString();
                    picName = fileMap.get("fileName").toString();
                }
            }
        }
        String alarmStr = fireCode + ";;" + picPath + ";;" + videoPath;
        String uuid = UUID.randomUUID().toString().replace("-", "");
        //存储在数据库
        AlarmAllDeviceDataChanged alarmAllDeviceDataChanged = new AlarmAllDeviceDataChanged();
        alarmAllDeviceDataChanged.setId(UUID.randomUUID().toString());
        alarmAllDeviceDataChanged.setJsondata(jsonParam.toString());
        alarmAllDeviceDataChangedMapper.insert(alarmAllDeviceDataChanged);

        VideoAlarmDeviceDataChanged videoAlarmDeviceDataChanged = new VideoAlarmDeviceDataChanged();
        videoAlarmDeviceDataChanged.setId(UUID.randomUUID().toString());
        videoAlarmDeviceDataChanged.setJsondata(jsonParam1.toString());
        videoAlarmDeviceDataChanged.setPath(picPath + ";;" + videoPath);
        videoAlarmDeviceDataChangedMapper.insert(videoAlarmDeviceDataChanged);
        //rest调用通知模块接口：
        jsonParamN.put("interfaceType", "1");
        jsonParamN.put("content", content);
        jsonParamN.put("alarmTypeName", alarmTypeName);
        jsonParamN.put("alarmtime", time);
        jsonParamN.put("deviceClassify", 6);
        jsonParamN.put("path", picPath + ";;" + videoPath);
        jsonParamN.put("uuid", uuid);
        jsonParamN.put("alarmStr", alarmStr);
        fireFightingiot(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo");
        //异步更新设备状态
        jsonParamN.put("state","2");
        asyncService.updateDeviceCurrentState(jsonParamN);
        //返回数据
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", "success");
        jsonObject.put("message", "创建成功");
        jsonObject.put("alarmId", uuid);
        System.out.println(jsonParamN.toString());
        return jsonObject;

    }

    /**
     * 消除报警
     *
     * @param request
     * @param jsonParam
     * @return
     * @throws Exception
     */
    public JSONObject VisualizationStop(HttpServletRequest request, Dict jsonParam) throws Exception {
        JSONObject jsonParam1 = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        logger.info("智瓴消除报警---------" + jsonParam1);
        JSONObject jsonParamN = new JSONObject();
        //设备号
        jsonParamN.put("number", jsonParam1.getStr("devId"));
        jsonParamN.put("uuid", jsonParam1.getStr("alarmId"));
        //上传文件到服务器
        String picPath = "";
        String picName = "";
        String videoPath = "";
        String videoName = "";
        Object object = uploadService.uploadFile(jsonParam, request);
        if (object instanceof List) {
            List<Map<String, Object>> fileList = (ArrayList) object;
            for (Map<String, Object> fileMap : fileList) {
                if (fileMap.get("filePath").toString().endsWith(".mp4")) {
                    videoPath = fileMap.get("filePath").toString();
                    videoName = fileMap.get("fileName").toString();
                } else {
                    picPath = fileMap.get("filePath").toString();
                    picName = fileMap.get("fileName").toString();
                }
            }
        }
        //存储在数据库
        VideoNormalDeviceDataChanged videoNormalDeviceDataChanged = new VideoNormalDeviceDataChanged();
        videoNormalDeviceDataChanged.setId(UUID.randomUUID().toString());
        videoNormalDeviceDataChanged.setJsondata(jsonParam1.toString());
        videoNormalDeviceDataChanged.setPath(videoPath);
        videoNormalDeviceDataChangedMapper.insert(videoNormalDeviceDataChanged);
        jsonParamN.put("interfaceType", "2");
        jsonParamN.put("deviceClassify", "6");
        jsonParamN.put("handlePerson", null);
        jsonParamN.put("infoconfirm", null);
        jsonParamN.put("handleRemark", null);
        jsonParamN.put("handletime", null);
        jsonParamN.put("handFlag", "2");
        jsonParamN.put("path", videoPath);
        fireFightingiot(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo");
        //返回数据
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", "success");
        jsonObject.put("message", "创建成功");
        System.out.println(jsonParamN.toString());
        return jsonObject;
    }

    /**
     * 萤石云视频解析
     *
     * @param jsonParam
     * @return
     * @throws Exception
     */
    public RespEntity fluoriteCloud(JSONObject jsonParam) throws Exception {
        logger.info("------------------------------------------------------fluoriteCloud--------------------------------------------------------");
        logger.info(jsonParam.toString());
        JSONObject jsonParamN = new JSONObject();
        //处理支持form-data和json两种方式
        //jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //---------解析开始-------------------------
        //header数据
        JSONObject header = jsonParam.getJSONObject("header");
        //设备号
        String number = header.getStr("deviceId");
        //body数据
        JSONObject body = jsonParam.getJSONObject("body");
        //报警类型
        String alarmType = body.getStr("alarmType");
        String alarmTypeName = "";

        if ("hightemperature".equals(alarmType) || "thermalimagingfire".equals(alarmType)) {
            alarmTypeName = "热成像火点";
        } else if ("leftdetection".equals(alarmType)) {
            alarmTypeName = "电动车识别报警";
        } else {
            return RespEntity.success();
        }
        //报警时间
        String alarmtime = body.getStr("alarmTime").replace("T", " ");
        //图片路径
        String pictureList = body.getStr("pictureList");
        JSONArray jsonArray = JSONArray.parseArray(pictureList);
        String path = "";
        for (Object object : jsonArray) {
            com.alibaba.fastjson.JSONObject jsonObject = (com.alibaba.fastjson.JSONObject) object;
            if (jsonObject.getString("id").endsWith("1")) {
                path = jsonObject.getString("url");
            }
        }
        String uuid = UUID.randomUUID().toString().replace("-", "");
        //存储在数据库
        VideoAlarmDeviceDataChanged videoAlarmDeviceDataChanged = new VideoAlarmDeviceDataChanged();
        videoAlarmDeviceDataChanged.setId(UUID.randomUUID().toString());
        videoAlarmDeviceDataChanged.setJsondata(jsonParam.toString());
        videoAlarmDeviceDataChanged.setPath(path);
        videoAlarmDeviceDataChangedMapper.insert(videoAlarmDeviceDataChanged);

        jsonParamN.put("interfaceType", "1");
        jsonParamN.put("number", number);
        jsonParamN.put("content", alarmTypeName);
        jsonParamN.put("alarmTypeName", alarmTypeName);
        jsonParamN.put("alarmtime", alarmtime);
        jsonParamN.put("deviceClassify", 6);
        jsonParamN.put("path", path);
        jsonParamN.put("uuid", uuid);
        //查询这个设备号这种类型的报警上次报警时间，如果时间间隔在1.5小时以内，不报警
//        List<AlarmRecord> alarmList = alarmRecordMapper.selectList(new QueryWrapper<AlarmRecord>().eq("number", number).eq("type", alarmTypeName));
//        if (alarmList.isEmpty()) {//没有记录时添加
//            AlarmRecord alarmRecord = new AlarmRecord();
//            alarmRecord.setNumber(number);
//            alarmRecord.setTime(DateUtil.now());
//            alarmRecord.setType(alarmTypeName);
//            alarmRecordMapper.insert(alarmRecord);
//        } else {//有记录时判断加修改
//            AlarmRecord alarmRecord = alarmList.get(0);
//            String times = alarmRecord.getTime();
//            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            boolean timeFlag = getDatePoor(new Date(), simpleDateFormat.parse(times), 6);
//            if (timeFlag) {
//                alarmRecord.setTime(DateUtil.now());
//                alarmRecordMapper.update(alarmRecord, new QueryWrapper<AlarmRecord>().eq("number", number).eq("type", alarmTypeName));
//            }else{
//                return RespEntity.success();
//            }
//        }
        //jsonParamN.put("alarmStr",alarmStr);
        restPostOrGet(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo", "POST");
        //异步更新设备状态
        jsonParamN.put("state","2");
        asyncService.updateDeviceCurrentState(jsonParamN);
        return RespEntity.success();
    }

    /**
     * aiBox视频解析
     *
     * @param jsonParam
     * @return
     * @throws Exception
     */
    public RespEntity aiBox(JSONObject jsonParam) throws Exception {
        logger.info("--------------------aiBox开始---------------:" + jsonParam);


        //报警信息的value
        JSONObject value = jsonParam.getJSONObject("value");
        //报警图片的信息
        String alarmPicPath = jsonParam.getStr("AlarmPicPath");
        //设备号(根据aiBox中的摄像头的deviceName)
        String number = value.getStr("DeviceName");
        //时间
        String time = contextLoads(jsonParam.getLong("time"));
        //报警类型
        String alarmType = value.getStr("AlarmType");
        //报警类型名称
        String alarmTypeName = "";
        String fireCode = "";
        if ("13001".equals(alarmType)) {
            alarmTypeName = "火灾烟雾报警";
            fireCode = "6003";
        } else if ("11004".equals(alarmType)) {
            alarmTypeName = "岗位监测报警";
            fireCode = "6002";
        } else if ("13002".equals(alarmType)) {
            alarmTypeName = "消防通道报警";
            fireCode = "6006";
        } else {
            return RespEntity.success();
        }
        String alarmStr = fireCode + ";;" + alarmPicPath + ";;" + alarmPicPath;
        String uuid = UUID.randomUUID().toString().replace("-", "");
        //存储在数据库
        VideoAlarmDeviceDataChanged videoAlarmDeviceDataChanged = new VideoAlarmDeviceDataChanged();
        videoAlarmDeviceDataChanged.setId(UUID.randomUUID().toString());
        videoAlarmDeviceDataChanged.setJsondata(jsonParam.toString());
        videoAlarmDeviceDataChanged.setPath(alarmPicPath);
        videoAlarmDeviceDataChangedMapper.insert(videoAlarmDeviceDataChanged);
        JSONObject jsonParamN = new JSONObject();
        jsonParamN.put("interfaceType", "1");
        jsonParamN.put("number", number);
        jsonParamN.put("content", alarmTypeName);
        jsonParamN.put("alarmTypeName", alarmTypeName);
        jsonParamN.put("alarmtime", time);
        jsonParamN.put("deviceClassify", 6);
        jsonParamN.put("path", alarmPicPath);
        jsonParamN.put("uuid", uuid);
        jsonParamN.put("alarmStr", alarmStr);
        restPostOrGet(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo", "POST");
        //异步更新设备状态
        jsonParamN.put("state","2");
        asyncService.updateDeviceCurrentState(jsonParamN);
        return RespEntity.success();
    }

    /**
     * 阿里云摄像头
     *
     * @param jsonParam
     * @return
     * @throws Exception
     */
    public JSONObject aliyunCamera(JSONObject jsonParam) throws Exception {
        logger.info("--------------------aliyunCamera开始---------------:" + jsonParam);
        JSONObject ret = new JSONObject();
        ret.put("errcode", 0);
        ret.put("errmsg", "ok");
        //报警信息的value
        JSONObject actionCard = jsonParam.getJSONObject("actionCard");
        //报警图片的信息
        String alarmPicPath = actionCard.getStr("singleURL");
        String picUrl = jsonParam.getStr("picUrl");
        //设备号(阿里摄像头的deviceName)
        String number = jsonParam.getStr("deviceName");
        //时间
        String time = contextLoads(jsonParam.getLong("taskTime"));
        //报警类型
        String eventType = jsonParam.getStr("eventType");
        //报警状态 PENDING是报警、CONTINUE是持续报警、CANCEL是解除
        String eventState = jsonParam.getStr("eventState");
        String fireCode = "";
        if (eventState.equals("PENDING") || eventState.equals("CONTINUE")) {
            //报警类型名称
            String alarmTypeName = "";
            //服务器图片地址
            String url = PictureDownload.downloadFile(picUrl);
            if ("AFK".equals(eventType)) {
                alarmTypeName = "岗位监测报警";
                fireCode = "6002";
            } else if ("FCO".equals(eventType)) {
                alarmTypeName = "消防通道报警";
                fireCode = "6006";
            } else if ("FLAME".equals(eventType)) {
                alarmTypeName = "明火识别";
                fireCode = "6003";
            }else if ("RI".equals(eventType)){
                alarmTypeName = "区域入侵";
                fireCode = "6004";
            } else {
                return ret;
            }
            String alarmStr = fireCode + ";;" + url + ";;" + url;
            //查询这个设备号这种类型的报警上次报警时间，如果时间间隔在2小时以内，不报警
            //为报警
            boolean insertAlarmFlag = true;
//            List<AlarmRecord> alarmList = alarmRecordMapper.selectList(new QueryWrapper<AlarmRecord>().eq("number", number).eq("type", alarmTypeName));
//            if (alarmList.isEmpty()) {//没有记录时添加
//                AlarmRecord alarmRecord = new AlarmRecord();
//                alarmRecord.setNumber(number);
//                alarmRecord.setTime(DateUtil.now());
//                alarmRecord.setType(alarmTypeName);
//                alarmRecordMapper.insert(alarmRecord);
//                insertAlarmFlag = true;
//            } else {//有记录时判断加修改
//                AlarmRecord alarmRecord = alarmList.get(0);
//                String times = alarmRecord.getTime();
//                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                boolean timeFlag = getDatePoor(new Date(), simpleDateFormat.parse(times), 5);
//                if (timeFlag) {
//                    alarmRecord.setTime(DateUtil.now());
//                    alarmRecordMapper.update(alarmRecord, new QueryWrapper<AlarmRecord>().eq("number", number).eq("type", alarmTypeName));
//                    insertAlarmFlag = true;
//                }
//            }
            if (insertAlarmFlag) {
                String uuid = UUID.randomUUID().toString().replace("-", "");
                //存储在数据库
                VideoAlarmDeviceDataChanged videoAlarmDeviceDataChanged = new VideoAlarmDeviceDataChanged();
                videoAlarmDeviceDataChanged.setId(UUID.randomUUID().toString());
                videoAlarmDeviceDataChanged.setJsondata(jsonParam.toString());
                videoAlarmDeviceDataChanged.setPath(alarmPicPath);
                videoAlarmDeviceDataChangedMapper.insert(videoAlarmDeviceDataChanged);
                JSONObject jsonParamN = new JSONObject();
                jsonParamN.put("interfaceType", "1");
                jsonParamN.put("number", number);
                jsonParamN.put("content", alarmTypeName);
                jsonParamN.put("alarmTypeName", alarmTypeName);
                jsonParamN.put("alarmtime", time);
                jsonParamN.put("deviceClassify", 6);
                jsonParamN.put("path", url);
                jsonParamN.put("uuid", uuid);
                jsonParamN.put("alarmStr", alarmStr);
                restPostOrGet(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo", "POST");
                //异步更新设备状态
                jsonParamN.put("state","2");
                asyncService.updateDeviceCurrentState(jsonParamN);
            }
        }

        //{"errcode":0,errmsg":"ok"}
        return ret;
    }
    /**
     * 海康超脑
     *
     * @param jsonParam
     * @return
     * @throws Exception
     */
    public RespEntity hkHyperbrain(JSONObject jsonParam) throws Exception {
        logger.info("--------------------hkHyperbrain开始---------------:" + jsonParam);
        //报警图片的信息
        String picUrl = jsonParam.getStr("picUrl");
        //设备号(阿里摄像头的deviceName)
        String number = jsonParam.getStr("struDevIP");
        //时间
        String time = DateUtil.now();
        //报警类型
        String eventType = jsonParam.getStr("lCommand");
        //报警类型名称
        String alarmTypeName = "";
        //服务器图片地址
        String url = PictureDownload.downloadPicture(picUrl);
        if ("0x1102".equals(eventType)) {
            alarmTypeName = "岗位监测报警";
        } else {
            return RespEntity.success();
        }
        //查询这个设备号这种类型的报警上次报警时间，如果时间间隔在2小时以内，不报警
        String uuid = UUID.randomUUID().toString().replace("-", "");
        //存储在数据库
        VideoAlarmDeviceDataChanged videoAlarmDeviceDataChanged = new VideoAlarmDeviceDataChanged();
        videoAlarmDeviceDataChanged.setId(UUID.randomUUID().toString());
        videoAlarmDeviceDataChanged.setJsondata(jsonParam.toString());
        videoAlarmDeviceDataChanged.setPath(picUrl);
        videoAlarmDeviceDataChangedMapper.insert(videoAlarmDeviceDataChanged);
        JSONObject jsonParamN = new JSONObject();
        jsonParamN.put("interfaceType", "1");
        jsonParamN.put("number", number);
        jsonParamN.put("content", alarmTypeName);
        jsonParamN.put("alarmTypeName", alarmTypeName);
        jsonParamN.put("alarmtime", time);
        jsonParamN.put("deviceClassify", 6);
        jsonParamN.put("path", url);
        jsonParamN.put("uuid", uuid);
        restPostOrGet(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo", "POST");
        //异步更新设备状态
        jsonParamN.put("state","2");
        asyncService.updateDeviceCurrentState(jsonParamN);
        return RespEntity.success();
    }
    /**
     * @Author YangYu
     * @Description 博观盒子卸油和人为合并（宇视）
     * @Date Created in 11:09 2022/2/24
     * @Param [jsonParam]
     */

    public RespEntity unloadingOilOrSafe(JSONObject jsonParam) throws Exception {
        if (jsonParam.containsKey("oil_results")) {
            return unloadingOilCamera(jsonParam);
        } else {
            return safeBox(jsonParam);
        }
    }

    /**
     * @Author YangYu
     * @Description 卸油监控上报
     * @Date Created in 16:23 2021/11/18
     * @Param [jsonParam]
     */

    public RespEntity unloadingOilCamera(JSONObject jsonParam) throws Exception {
        try {
            //原始数据
            cn.hutool.json.JSONArray dataJsonArray = jsonParam.getJSONArray("oil_results");
            JSONObject dataJson = (JSONObject) dataJsonArray.get(0);
            //设备号
            String number = dataJson.getStr("serial_number");
            //通道号
            String channelId = dataJson.getStr("channel_id");
            //时间
            String time = contextLoads(dataJson.getLong("timestamp") * 1000);
            //步骤类型
            String stepType = dataJson.getStr("step_type");
            //步骤状态
            String stepStatus = dataJson.getStr("step_status");
            //图片路径
            JSONObject bigImage = dataJson.getJSONObject("big_image");
            String picUrl = PictureDownload.base64ToIo(bigImage.getStr("Image"),"AOX-H01");
            //步骤类型名称
            String stepTypeName = "";
            if (StrUtil.isBlank(stepType)) {
                return RespEntity.success();
            } else {
                stepTypeName = stepTypeOrStepStatus(stepType);
            }
            String uuid = UUID.randomUUID().toString().replace("-", "");
            JSONObject jsonParamN = new JSONObject();
            jsonParamN.put("interfaceType", "1");
            jsonParamN.put("number", number+channelId);
            jsonParamN.put("content", stepTypeName + " 状态:" + stepTypeOrStepStatus(stepStatus));
            jsonParamN.put("alarmTypeName", "卸油分析");
            jsonParamN.put("alarmtime", time);
            jsonParamN.put("deviceClassify", 6);
            jsonParamN.put("path", picUrl);
            jsonParamN.put("uuid", uuid);
            jsonParamN.put("alarmStr", "6002;;url;;url");
            restPostOrGet(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo", "POST");
            //异步更新设备状态
            jsonParamN.put("state","2");
            asyncService.updateDeviceCurrentState(jsonParamN);
        } catch (Exception e) {
            logger.info(e.toString());
        }
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 安消aibox
     * @Date Created in 17:02 2021/11/22
     * @Param [jsonParam]
     */

    public RespEntity safeBox(JSONObject jsonParam) throws Exception {
        // 报警恢复
        if (jsonParam.containsKey("AlarmRecovers")){
            cn.hutool.json.JSONArray dataJsonArray = jsonParam.getJSONArray("AlarmRecovers");
            JSONObject dataJson = (JSONObject) dataJsonArray.get(0);
            //设备号
            String number = dataJson.getStr("SerialNumber");
            //通道号
            String channelId = dataJson.getStr("ChannelId");
            JSONObject jsonParamN = new JSONObject();
            jsonParamN.put("number",number+channelId);
            jsonParamN.put("state","1");
            asyncService.updateDeviceCurrentState(jsonParamN);
            return RespEntity.success();
        }
        //原始数据
        cn.hutool.json.JSONArray dataJsonArray = jsonParam.getJSONArray("BehaviorResults");
        JSONObject dataJson = (JSONObject) dataJsonArray.get(0);
        //设备号
        String number = dataJson.getStr("SerialNumber");
        //时间
        String time = contextLoads(dataJson.getLong("Timestamp") * 1000);
        //通道号
        String channelId = dataJson.getStr("ChannelId");
        //报警类型
        String alarmType = dataJson.getStr("AlarmType");
        //图片路径
        JSONObject bigImage = dataJson.getJSONObject("BigImage");
        String picUrl = PictureDownload.base64ToIo(bigImage.getStr("Image"),"AOX-H01");
        String alarmTypeName = "";
        String content = "";
        if (alarmType.equals("4") || alarmType.equals("5") || alarmType.equals("6") || alarmType.equals("7") || alarmType.equals("19")) {
            alarmTypeName = "人员检测";
            content = safeBoxAlarmType(alarmType);
        } else if (alarmType.equals("8")) {
            alarmTypeName = "火灾烟雾报警";
            content = safeBoxAlarmType(alarmType);
        } else if (alarmType.equals("17") || alarmType.equals("16")) {
            alarmTypeName = "岗位监测报警";
            content = safeBoxAlarmType(alarmType);
        } else if (alarmType.equals("22") || alarmType.equals("18")) {
            alarmTypeName = "消防通道报警";
            content = safeBoxAlarmType(alarmType);
        } else if (alarmType.equals("20")) {
            alarmTypeName = "区域入侵";
            content = safeBoxAlarmType(alarmType);
        } else if (alarmType.equals("21")) {
            alarmTypeName = "电动车识别报警";
            content = safeBoxAlarmType(alarmType);
        } else {
            return RespEntity.fail("未设定报警类型!");
        }
        String uuid = UUID.randomUUID().toString().replace("-", "");
        JSONObject jsonParamN = new JSONObject();
        jsonParamN.put("interfaceType", "1");
        jsonParamN.put("number", number+channelId);
        jsonParamN.put("content", content);
        jsonParamN.put("alarmTypeName", alarmTypeName);
        jsonParamN.put("alarmtime", time);
        jsonParamN.put("deviceClassify", 6);
        jsonParamN.put("path", picUrl);
        jsonParamN.put("uuid", uuid);
        jsonParamN.put("alarmStr", "6002;;url;;url");
        restPostOrGet(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo", "POST");
        //异步更新设备状态
        jsonParamN.put("state","2");
        asyncService.updateDeviceCurrentState(jsonParamN);
        jsonParamN.put("ChannelId",dataJson.getStr("ChannelId"));
        jsonParamN.put("image",bigImage.getStr("Image"));
        //异步对接安工院
        //asyncService.postGasStation(jsonParamN);
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 浪潮
     * @Date Created in 16:55 2022/4/15
     * @Param [jsonParam]
     */

    public RespEntity waveBox(JSONObject jsonParam) throws Exception {
        //设备号
        String number = jsonParam.getStr("devId");
        //报警id
        String alarmId = jsonParam.getStr("alarmId");
        //时间
        String time = dateConvert(jsonParam.getStr("alarmDate"));
        //报警类型
        String alarmType = jsonParam.getStr("alarmType");
        //上传文件到服务器
        String picUrl = PictureDownload.base64ToIo(jsonParam.getStr("alarmImage"),"waveBox");
        String alarmTypeName = "";
        String content = "";
        if (alarmType.equals("7") || alarmType.equals("8") || alarmType.equals("9") || alarmType.equals("6") || alarmType.equals("1") || alarmType.equals("5")) {
            alarmTypeName = "人员检测";
            content = waveBoxAlarmType(alarmType);
        } else if (alarmType.equals("11")) {
            alarmTypeName = "火灾烟雾报警";
            content = waveBoxAlarmType(alarmType);
        } else if (alarmType.equals("3") ) {
            alarmTypeName = "岗位监测报警";
            content = waveBoxAlarmType(alarmType);
        } else if (alarmType.equals("2")) {
            alarmTypeName = "区域入侵";
            content = waveBoxAlarmType(alarmType);
        } else if (alarmType.equals("10")) {
            alarmTypeName = "明火识别";
            content = waveBoxAlarmType(alarmType);
        }else if (alarmType.equals("12") || alarmType.equals("13") || alarmType.equals("14")) {
            alarmTypeName = "卸油分析";
            content = waveBoxAlarmType(alarmType);
        } else {
            return RespEntity.fail("未设定报警类型!");
        }
        JSONObject jsonParamN = new JSONObject();
        jsonParamN.put("interfaceType", "1");
        jsonParamN.put("number", number);
        jsonParamN.put("content", content);
        jsonParamN.put("alarmTypeName", alarmTypeName);
        jsonParamN.put("alarmtime", time);
        jsonParamN.put("deviceClassify", 6);
        jsonParamN.put("path", picUrl);
        jsonParamN.put("uuid", alarmId);
        jsonParamN.put("alarmStr", "6002;;url;;url");
        restPostOrGet(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo", "POST");
        //异步更新设备状态
        jsonParamN.put("state","2");
        asyncService.updateDeviceCurrentState(jsonParamN);
        return RespEntity.success();
    }


    /**
     * @Author YangYu
     * @Description 安消报警类型
     * @Date Created in 14:29 2021/11/23
     * @Param [alarmType]
     */

    public String waveBoxAlarmType(String alarmType) {
        Map<String, String> map = new HashMap<>();
        //报警数据
        map.put("1", "翻越围栏");
        map.put("2", "区域入侵");
        map.put("3", "人员离岗");
        map.put("5", "人员聚集");
        map.put("6", "打电话");
        map.put("7", "抽烟");
        map.put("8", "未佩戴安全帽");
        map.put("9", "未穿着工作服");
        map.put("10", "明火识别");
        map.put("11", "烟雾识别");
        map.put("12", "静电夹使用或静电标识的摆放");
        map.put("13", "灭火器是否摆放在作业区域");
        map.put("14", "是否在静电释放15分钟后，开始进行卸油作业");
        return map.get(alarmType);
    }
    /**
     * @Author YangYu
     * @Description 安消报警类型
     * @Date Created in 14:29 2021/11/23
     * @Param [alarmType]
     */

    public String safeBoxAlarmType(String alarmType) {
        Map<String, String> map = new HashMap<>();
        //报警数据
        map.put("4", "未戴安全帽检测");
        map.put("5", "未穿工服");
        map.put("6", "打电话检测");
        map.put("7", "吸烟检测");
        map.put("8", "烟火检测");
        map.put("16", "睡岗检测");
        map.put("17", "离岗检测");
        map.put("18", "通道阻塞");
        map.put("19", "物品遗失");
        map.put("20", "区域入侵");
        map.put("21", "电动车禁入");
        map.put("22", "消防车通道占用");
        return map.get(alarmType);
    }

    /**
     * @Author YangYu
     * @Description 卸油步骤类型
     * @Date Created in 10:46 2021/11/19
     * @Param [stepType]
     */

    public String stepTypeOrStepStatus(String stepType) {
        Map<String, String> map = new HashMap<>();
        //报警数据
        map.put("23", "油罐车入位");
        map.put("24", "轮挡放置");
        map.put("25", "放置安全装置");
        map.put("26", "安全操作");
        map.put("27", "油品接卸");
        map.put("28", "油品留样");
        map.put("29", "人员值守");
        map.put("30", "卸后确认");
        map.put("1", "合格");
        map.put("2", "不合格");
        return map.get(stepType);
    }

    /**
     * 将毫秒转化为日期(格式:yyyy-MM-dd hh:mm:ss)
     *
     * @param l
     * @return
     * @throws Exception
     */
    public String contextLoads(Long l) throws Exception {

        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
        Date date = new Date(l);
        String str1 = sdf1.format(date);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date2 = sdf.parse(str1);
        String str2 = sdf.format(date2);
        return str2;
    }
    /**
     * 将yyyyMMddHHmmss转化为日期(格式:yyyy-MM-dd hh:mm:ss)
     * @param date
     * @return
     * @throws Exception
     */
    public String dateConvert(String date) throws Exception {

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        LocalDateTime ldt = LocalDateTime.parse(date,dtf);
        DateTimeFormatter fa = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String datetime2 = ldt.format(fa);
        return datetime2;
    }

    /**
     * @Author YangYu
     * @Description 大华云睿（电动车识别）
     * @Date Created in 11:01 2022/1/21
     * @Param [jsonParam]
     */

    public RespEntity daHuaYunRui(JSONObject jsonParam) throws Exception {
        logger.info("进service---------"+jsonParam);
        //报警类型
        String msgType = jsonParam.getStr("msgType");
        //报警时间
        String time = contextLoads(jsonParam.getLong("time"));
        //消息ID
        String messageId = jsonParam.getStr("messageId");
        //获取token
        String token = getDaHuaYunRuiToken(jsonParam,"firefightingiot","getDaHuaYunRuiToken","device");
        logger.info("token---------"+token);
        //获取报警消息详情
        JSONObject messageInfo = new JSONObject();
        messageInfo.put("messageId",messageId);
        //TODO 大华那边图片处理需要10秒左右
        Thread.sleep(10000);
        JSONObject message = restDHYR(messageInfo,"dahua","messageInfo","DaHuaYunRui",token,"POST");
        logger.info("message---------"+message);
        String urls = message.getJSONObject("data").getJSONArray("picurlArray").get(1).toString();
        String url = PictureDownload.downloadFile(urls);
        //设备号
        String number = jsonParam.getStr("deviceId");
        //报警类型名称
        String alarmTypeName = "";
        if ("nonMotorEntrying".equals(msgType)){
            alarmTypeName = "电动车识别报警";
        }else {
            return RespEntity.success();
        }
        String uuid = UUID.randomUUID().toString().replace("-","");
        //存储在数据库
        VideoAlarmDeviceDataChanged videoAlarmDeviceDataChanged = new VideoAlarmDeviceDataChanged();
        videoAlarmDeviceDataChanged.setId(UUID.randomUUID().toString());
        videoAlarmDeviceDataChanged.setJsondata(jsonParam.toString());
        videoAlarmDeviceDataChanged.setPath(url);
        videoAlarmDeviceDataChangedMapper.insert(videoAlarmDeviceDataChanged);
        JSONObject jsonParamN = new JSONObject();
        jsonParamN.put("interfaceType","1");
        jsonParamN.put("number",number);
        jsonParamN.put("content",alarmTypeName);
        jsonParamN.put("alarmTypeName",alarmTypeName);
        jsonParamN.put("alarmtime",time);
        jsonParamN.put("deviceClassify",6);
        jsonParamN.put("path",url);
        jsonParamN.put("uuid",uuid);
        restPostOrGet(jsonParamN,"communication","notificationAlarmHandel","alarmInfo","POST");
        //异步更新设备状态
        jsonParamN.put("state","2");
        asyncService.updateDeviceCurrentState(jsonParamN);
        return RespEntity.success();
    }
    /**
     * @Author YangYu
     * @Description 大华云睿获取token专用
     * @Date Created in 14:24 2022/1/21
     * @Param [jsonParam, configKey, key, gp]
     */

    public String getDaHuaYunRuiToken(JSONObject jsonParam,String configKey,String key,String gp){
        String ip = ConfigKit.getStr(configKey,"config");
        String methodPath = FirefightingiotKit.getStr(key,gp);
        String domain = ip + methodPath;
        String xml = "";
        xml = HttpUtil.get(domain,jsonParam);
        return xml;
    }


    /**
     * @Author YangYu
     * @Description 海康梯控
     * @Date Created in 10:06 2021/3/18
     * @Param [jsonParam]
     */

    public RespEntity hikvision(JSONObject jsonParam) throws Exception {
        logger.info("hikvision" + "------" + jsonParam);
        try {
            //最外层数据
            JSONObject params = jsonParam.getJSONObject("params");
            //ability不为空解析
            if (params.getStr("ability").equals("")) {
                cn.hutool.json.JSONArray events = params.getJSONArray("events");
                if (events.size() != 1) {
                    return RespEntity.success();
                }
                JSONObject event = (JSONObject) events.get(0);
                cn.hutool.json.JSONArray eventDetails = event.getJSONArray("eventDetails");
                JSONObject eventDetail = (JSONObject) eventDetails.get(0);
                //异步更新关门参数
                asyncService.updateHKCamera(eventDetail);
                //图片
                cn.hutool.json.JSONArray linkageResults = event.getJSONArray("linkageResult");
                JSONObject linkageResult = (JSONObject) linkageResults.get(0);
                cn.hutool.json.JSONArray contents = linkageResult.getJSONArray("content");
                JSONObject content = (JSONObject) contents.get(0);
                cn.hutool.json.JSONArray picUrls = content.getJSONArray("picUrls");
                String picUrl = (String) picUrls.get(0);
                String svrIndexCode = content.getStr("svrIndexCode");
                String url = uploadService.queryHkVideoImage(svrIndexCode, picUrl);
                //时间
                //String time = contextLoads(params.getStr("sendTime"));
                String[] sendTime = params.getStr("sendTime").split("T");
                String s = sendTime[1];
                String time = sendTime[0] + " " + s.substring(0, s.lastIndexOf("."));
                //String time = DateUtil.now();
                //设备号
                String number = eventDetail.getStr("srcIndex");
                //报警类型
                String eventType = eventDetail.getStr("eventType");
                //报警类型名称
                String alarmTypeName = "";
                if (eventType.equals("131330")) {
                    alarmTypeName = "遮挡报警";
                    //TODO 后期需要遮挡报警把return去掉！
                    return RespEntity.success();
                }
                if (eventType.equals("131594")) {
                    alarmTypeName = "电动车识别报警";
                }
                String uuid = UUID.randomUUID().toString().replace("-", "");
                //存储在数据库
                VideoAlarmDeviceDataChanged videoAlarmDeviceDataChanged = new VideoAlarmDeviceDataChanged();
                videoAlarmDeviceDataChanged.setId(UUID.randomUUID().toString());
                videoAlarmDeviceDataChanged.setJsondata(jsonParam.toString());
                videoAlarmDeviceDataChanged.setPath(url);
                videoAlarmDeviceDataChangedMapper.insert(videoAlarmDeviceDataChanged);
                JSONObject jsonParamN = new JSONObject();
                jsonParamN.put("interfaceType", "1");
                jsonParamN.put("number", number);
                jsonParamN.put("content", alarmTypeName);
                jsonParamN.put("alarmTypeName", alarmTypeName);
                jsonParamN.put("alarmtime", time);
                jsonParamN.put("deviceClassify", 6);
                jsonParamN.put("path", url);
                jsonParamN.put("uuid", uuid);
                restPostOrGet(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo", "POST");
                //异步更新设备状态
                jsonParamN.put("state","2");
                asyncService.updateDeviceCurrentState(jsonParamN);
            }
        } catch (Exception e) {
            return RespEntity.fail("数据格式不正确!");
        }
        return RespEntity.success();
    }

    /**
     * @Author LiHaoDong
     * @Description 事件订阅回调
     * @Date Created in 10:06 2021/3/18
     * @Param [jsonParam]
     */
    public RespEntity eventSubscriptionsHKRest(JSONObject jsonParam) throws IOException {
        logger.info("eventSubscriptionsHKRest" + "------" + jsonParam);
        try {
            //最外层数据
            JSONObject params = jsonParam.getJSONObject("params");
            //ability不为空解析
            if (params.getStr("ability").equals("")) {
                cn.hutool.json.JSONArray events = params.getJSONArray("events");
                if (events.size() != 1) {
                    return RespEntity.success();
                }
                JSONObject event = (JSONObject) events.get(0);
                cn.hutool.json.JSONArray eventDetails = event.getJSONArray("eventDetails");
                JSONObject eventDetail = (JSONObject) eventDetails.get(0);
                JSONObject data = eventDetail.getJSONObject("data");
                //时间
                String[] sendTime = data.getStr("dateTime").split("T");
                String s = sendTime[1];
                String time = sendTime[0] + " " + s.substring(0, s.lastIndexOf("."));
                //设备号
                String number = "";
                //报警类型
                String eventType = eventDetail.getStr("eventType");
                //图片
                String content = event.getJSONArray("linkageResult").getJSONObject(0).getStr("content");
                cn.hutool.json.JSONArray jsonContent = JSONUtil.parseArray(content);
                String picUrls = (String) jsonContent.getJSONObject(0).getJSONArray("picUrls").get(0);
                String svrIndexCode = jsonContent.getJSONObject(0).getStr("svrIndexCode");
                String url = uploadService.queryHkVideoImage(svrIndexCode, picUrls);
                //报警类型名称
                String alarmTypeName = "";
                if (eventType.equals("131585")) {
                    number = data.getJSONArray("linedetection").getJSONObject(0).getJSONObject("targetAttrs").getStr("cameraIndexCode");
                    alarmTypeName = "越界侦测";
                } else if (eventType.equals("131586")) {
                    number = data.getJSONArray("regionEntrance").getJSONObject(0).getJSONObject("targetAttrs").getStr("cameraIndexCode");
                    alarmTypeName = "进入区域";
                } else if (eventType.equals("131588")) {
                    number = data.getJSONArray("fielddetection").getJSONObject(0).getJSONObject("targetAttrs").getStr("cameraIndexCode");
                    alarmTypeName = "区域入侵";
                }
                String uuid = UUID.randomUUID().toString().replace("-", "");
                //存储在数据库
                VideoAlarmDeviceDataChanged videoAlarmDeviceDataChanged = new VideoAlarmDeviceDataChanged();
                videoAlarmDeviceDataChanged.setId(UUID.randomUUID().toString());
                videoAlarmDeviceDataChanged.setJsondata(jsonParam.toString());
                videoAlarmDeviceDataChanged.setPath(url);
                videoAlarmDeviceDataChangedMapper.insert(videoAlarmDeviceDataChanged);
                JSONObject jsonParamN = new JSONObject();
                jsonParamN.put("interfaceType", "1");
                jsonParamN.put("number", number);
                jsonParamN.put("content", alarmTypeName);
                jsonParamN.put("alarmTypeName", alarmTypeName);
                jsonParamN.put("alarmtime", time);
                jsonParamN.put("deviceClassify", 6);
                jsonParamN.put("path", url);
                jsonParamN.put("uuid", uuid);
                System.out.println("++++++++++++++++++" + jsonParamN.toString());
                restPostOrGet(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo", "POST");
                //异步更新设备状态
                jsonParamN.put("state","2");
                asyncService.updateDeviceCurrentState(jsonParamN);
            }
        } catch (Exception e) {
            return RespEntity.fail("数据格式不正确!");
        }
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 海康(加油站)
     * @Date Created in 10:06 2021/3/18
     * @Param [jsonParam]
     */

    public RespEntity hikGasStation(JSONObject jsonParam) throws Exception {
        logger.info("hikGasStation" + "------" + jsonParam);
        try {
            //最外层数据
            JSONObject params = jsonParam.getJSONObject("params");
            //ability不为空解析
            if (params.getStr("ability").equals("")) {
                cn.hutool.json.JSONArray events = params.getJSONArray("events");
                if (events.size() != 1) {
                    return RespEntity.success();
                }
                JSONObject event = (JSONObject) events.get(0);
                cn.hutool.json.JSONArray eventDetails = event.getJSONArray("eventDetails");
                JSONObject eventDetail = (JSONObject) eventDetails.get(0);
                //图片
                cn.hutool.json.JSONArray linkageResults = event.getJSONArray("linkageResult");
                JSONObject linkageResult = (JSONObject) linkageResults.get(0);
                cn.hutool.json.JSONArray contents = linkageResult.getJSONArray("content");
                JSONObject content = (JSONObject) contents.get(0);
                cn.hutool.json.JSONArray picUrls = content.getJSONArray("picUrls");
                String picUrl = (String) picUrls.get(0);
                String svrIndexCode = content.getStr("svrIndexCode");
                String url = uploadService.queryHkVideoImage(svrIndexCode, picUrl);
                //时间
                //String time = contextLoads(params.getStr("sendTime"));
                String[] sendTime = params.getStr("sendTime").split("T");
                String s = sendTime[1];
                String time = sendTime[0] + " " + s.substring(0, s.lastIndexOf("."));
                //String time = DateUtil.now();
                //设备号
                String number = eventDetail.getStr("srcIndex");
                //报警类型
                String eventType = eventDetail.getStr("eventType");
                HikEvent hikEvent = hikEventMapper.selectById(eventType);
                //报警类型名称
                String alarmTypeName = hikEvent.getGroupName();
                //报警内容
                String alarmContent = hikEvent.getContent();
                String uuid = UUID.randomUUID().toString().replace("-", "");
                JSONObject jsonParamN = new JSONObject();
                jsonParamN.put("interfaceType", "1");
                jsonParamN.put("number", number);
                jsonParamN.put("content", alarmContent);
                jsonParamN.put("alarmTypeName", alarmTypeName);
                jsonParamN.put("alarmtime", time);
                jsonParamN.put("deviceClassify", 6);
                jsonParamN.put("path", url);
                jsonParamN.put("uuid", uuid);
                restPostOrGet(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo", "POST");
                jsonParamN.put("alarmTypeCode", hikEvent.getAlarmType());
                jsonParamN.put("ChannelId", number);
            }
        } catch (Exception e) {
            return RespEntity.fail("数据格式不正确!");
        }
        return RespEntity.success();
    }

    /**
     * 云从加油站分析仪
     * @param jsonParam
     * @return
     * @throws Exception
     */
    public RespEntity yunCongGasStationAnalyzer(JSONObject jsonParam) throws Exception {

        //数据
        JSONObject strJsonData = jsonParam.getJSONObject("strJsonData");
        //分析仪设备号
        String deviceId = jsonParam.getStr("deviceId");
        //通道id
        String cameraId = strJsonData.getStr("cameraId");
        //报警时间
        String alarmTime = strJsonData.getStr("alarmTime");
        //主题类型 1非作业报警数据上报 2作业报警数据上报 3作业任务数据上报
        String type = jsonParam.getStr("type");
        //报警类型
        String alarmType = strJsonData.getStr("alarmType");
        //报警id
        String id = strJsonData.getStr("id");
        //报警图片
        String url = jsonParam.getStr("url");
        //报警类型名称
        String alarmTypeName = "";
        //报警内容
        String content = "";
        if (type.equals("1")){
            if (alarmType.equals("1")){
                alarmTypeName = "岗位监测报警";
                content = "人员离岗";
            }else if (alarmType.equals("2")){
                alarmTypeName = "人员检测";
                content = "灭火器报警";
            }else if (alarmType.equals("4")){
                alarmTypeName = "人员检测";
                content = "打电话";
            }else if (alarmType.equals("5")){
                alarmTypeName = "人员检测";
                content = "抽烟";
            }else if (alarmType.equals("6")){
                alarmTypeName = "明火识别";
                content = "烟火";
            }else {
                return RespEntity.success();
            }
        }else if (type.equals("2")){
            if (alarmType.equals("1")){
                alarmTypeName = "岗位监测报警";
                content = "人员离岗";
            }else if (alarmType.equals("2")){
                alarmTypeName = "人员检测";
                content = "灭火器报警";
            }else if (alarmType.equals("3")){
                alarmTypeName = "人员检测";
                content = "静电释放报警";
            }else {
                return RespEntity.success();
            }
        }else {
            if (alarmType.equals("1")){
                alarmTypeName = "卸油分析";
                content = "车辆进入";
            }else if (alarmType.equals("2")){
                alarmTypeName = "人员检测";
                content = "开始静电释放";
            }else if (alarmType.equals("3")){
                alarmTypeName = "人员检测";
                content = "灭火器抓拍";
            }else if (alarmType.equals("4")){
                alarmTypeName = "卸油分析";
                content = "卸油开始";
            }else if (alarmType.equals("5")){
                alarmTypeName = "卸油分析";
                content = "卸油结束";
            }else if (alarmType.equals("6")){
                alarmTypeName = "卸油分析";
                content = "车辆离开";
            }else {
                return RespEntity.success();
            }
        }
        //存储在数据库
        VideoAlarmDeviceDataChanged videoAlarmDeviceDataChanged = new VideoAlarmDeviceDataChanged();
        videoAlarmDeviceDataChanged.setId(UUID.randomUUID().toString());
        videoAlarmDeviceDataChanged.setJsondata(jsonParam.toString());
        videoAlarmDeviceDataChanged.setPath(url);
        videoAlarmDeviceDataChangedMapper.insert(videoAlarmDeviceDataChanged);
        JSONObject jsonParamN = new JSONObject();
        jsonParamN.put("interfaceType", "1");
        jsonParamN.put("number", deviceId+cameraId);
        jsonParamN.put("content", alarmTypeName);
        jsonParamN.put("alarmTypeName", alarmTypeName);
        jsonParamN.put("alarmtime", alarmTime);
        jsonParamN.put("deviceClassify", 6);
        jsonParamN.put("path", url);
        jsonParamN.put("uuid", id);
        System.out.println("++++++++++++++++++" + jsonParamN.toString());
        //restPostOrGet(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo", "POST");
        return RespEntity.success();
    }
    public RespEntity eventSubscriptionsHK(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //
        /*jsonParam.put("eventTypes","131585");
        jsonParam.put("eventDest","http://121.89.184.226:8101/video/eventSubscriptionsHKRest");*/

        /*jsonParam.put("eventTypes","131330");
        jsonParam.put("eventDest","http://121.89.184.226:8101/video/hikvision");*/
        jsonParam.put("eventTypes", "131594");
        jsonParam.put("eventDest", "http://121.89.184.226:8101/video/hikvision");
        //区域入侵
        /*jsonParam.put("eventTypes","131588");
        jsonParam.put("eventDest","http://121.89.184.226:8101/video/eventSubscriptionsHKRest");*/
        /*jsonParam.put("eventDest","http://121.89.184.226:8101/video/regionalIntrusionRest");*/
        //进入区域
        /*jsonParam.put("eventTypes","131586");
        jsonParam.put("eventDest","http://121.89.184.226:8101/video/eventSubscriptionsHKRest");*/
        //jsonParam.put("eventDest","http://121.89.184.226:8101/video/enterthezone");
        /**
         * STEP1：设置平台参数，根据实际情况,设置host appkey appsecret 三个参数.
         */
        ArtemisConfig.host = "122.4.227.102:4433"; // artemis网关服务器ip端口
        ArtemisConfig.appKey = "24769112";  // 秘钥appkey
        ArtemisConfig.appSecret = "NxjYIfempoqQaVtRqKLF";// 秘钥appSecret

        /**
         * STEP2：设置OpenAPI接口的上下文
         */
        final String ARTEMIS_PATH = "/artemis";

        /**
         * STEP3：设置接口的URI地址
         */
        final String previewURLsApi = ARTEMIS_PATH + "/api/eventService/v1/eventSubscriptionByEventTypes";
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", previewURLsApi);//根据现场环境部署确认是http还是https
            }
        };

        /**
         * STEP4：设置参数提交方式
         */
        String contentType = "application/json";

        /**
         * STEP5：组装请求参数
         */
        JSONObject jsonBody = new JSONObject();
        cn.hutool.json.JSONArray jsonArray = new cn.hutool.json.JSONArray();
        jsonArray.put(jsonParam.getInt("eventTypes"));
        jsonBody.put("eventTypes", jsonArray);
        jsonBody.put("eventDest", jsonParam.getStr("eventDest"));
        jsonBody.put("subType", 1);
        String body = jsonBody.toString();
        /**
         * STEP6：调用接口
         */
        String result = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, contentType, null);// post请求application/json类型参数
        return RespEntity.success(result);
    }

    /**
     * @Author YangYu
     * @Description 融合永道视频分析
     * @Date Created in 17:06 2023/2/22
     * @Param [jsonParam]
     */

    public RespEntity rongHeYongDao(JSONObject jsonParam) throws Exception {

        //视频分析仪设备号
        String hostCode = jsonParam.getStr("HostCode");
        //通道号
        String chnId = jsonParam.getStr("ChnId");
        //规则类型
        String ruleType = jsonParam.getStr("RuleType");
        //时间
        String time = rongHeYongDaoTime(jsonParam.getStr("Time"));
        //报警类型名称
        String alarmTypeName = "";
        //报警内容
        String content = "";
        if ("4".equals(ruleType)) {
            alarmTypeName = "岗位监测报警";
            content = "岗位监测报警";
        } else if ("1".equals(ruleType)) {
            alarmTypeName = "消防通道报警";
            content = "消防通道占用";
        }else if ("2".equals(ruleType)) {
            alarmTypeName = "区域入侵";
            content = "区域入侵";
        } else if ("12".equals(ruleType)) {
            alarmTypeName = "明火识别";
            content = "烟火识别";
        }else if ("3".equals(ruleType)) {
            alarmTypeName = "人员检测";
            content = "绊线探测";
        }else if ("7".equals(ruleType)) {
            alarmTypeName = "人群惊扰报警";
            content = "人群聚集";
        }else if ("10".equals(ruleType)) {
            alarmTypeName = "人员检测";
            content = "有人跌倒";
        }else if ("13".equals(ruleType)) {
            alarmTypeName = "人员检测";
            content = "打电话";
        }else if ("14".equals(ruleType)) {
            alarmTypeName = "人员检测";
            content = "未戴安全帽";
        }else if ("20".equals(ruleType)) {
            alarmTypeName = "人员检测";
            content = "有人吸烟";
        }else if ("35".equals(ruleType)) {
            alarmTypeName = "进入区域";
            content = "车牌识别";
        }else if ("46".equals(ruleType)) {
            alarmTypeName = "人员检测";
            content = "设备区开门";
        }else if ("52".equals(ruleType)) {
            alarmTypeName = "消防通道报警";
            content = "设备区开门";
        }else if ("30".equals(ruleType)) {
            alarmTypeName = "垃圾探测";
            content = "垃圾探测";
        } else {
            return RespEntity.fail("未解析类型,请联系开发人员!");
        }
        //图片
        String picUrl = "";
        if (jsonParam.containsKey("Pic2_base64") && !jsonParam.getStr("Pic2_base64").equals("null")){
            picUrl = PictureDownload.base64ToIo(jsonParam.getStr("Pic2_base64"),"rongheyongdao");
        }else {
            picUrl = PictureDownload.base64ToIo(jsonParam.getStr("Pic1_base64"),"rongheyongdao");
        }
        boolean insertAlarmFlag = false;
        //查询这个设备号这种类型的报警上次报警时间，如果时间间隔在2小时以内，不报警
        List<AlarmRecord> alarmList = alarmRecordMapper.selectList(new QueryWrapper<AlarmRecord>().eq("number", hostCode+chnId).eq("type", alarmTypeName));
        if (alarmList.isEmpty()) {//没有记录时添加
            AlarmRecord alarmRecord = new AlarmRecord();
            alarmRecord.setNumber(hostCode+chnId);
            alarmRecord.setTime(DateUtil.now());
            alarmRecord.setType(alarmTypeName);
            alarmRecordMapper.insert(alarmRecord);
            insertAlarmFlag = true;
        } else {//有记录时判断加修改
            AlarmRecord alarmRecord = alarmList.get(0);
            String times = alarmRecord.getTime();
            boolean timeFlag = DateUtils.judgmentDate(times,0.5);
            if (timeFlag) {
                alarmRecord.setTime(DateUtil.now());
                alarmRecordMapper.update(alarmRecord, new QueryWrapper<AlarmRecord>().eq("number", hostCode+chnId).eq("type", alarmTypeName));
                insertAlarmFlag = true;
            }
        }
        if (insertAlarmFlag){
            JSONObject jsonParamN = new JSONObject();
            jsonParamN.put("interfaceType", "1");
            jsonParamN.put("number", hostCode+chnId);
            jsonParamN.put("content", content);
            jsonParamN.put("alarmTypeName", alarmTypeName);
            jsonParamN.put("alarmtime", time);
            jsonParamN.put("deviceClassify", 6);
            jsonParamN.put("path", picUrl);
            jsonParamN.put("uuid", UUID.randomUUID().toString());
            restPostOrGet(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo", "POST");
            //异步更新设备状态
            jsonParamN.put("state","2");
            asyncService.updateDeviceCurrentState(jsonParamN);
        }
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 火焰报警摄像机（京电云4G）
     * @Date Created in 17:06 2023/2/22
     * @Param [jsonParam]
     */

    public RespEntity flameJDY(JSONObject jsonParam) throws Exception {

        //视频分析仪设备号
        String serialNumber = jsonParam.getStr("serialNumber");
        JSONObject jsonParamN = new JSONObject();
        //时间
        String time = DateUtil.now();
        if (jsonParam.containsKey("payload")){
            JSONObject jsonObject = jsonParam.getJSONArray("payload").getJSONObject(0);
            String remark = jsonObject.getStr("remark");
            //报警类型名称
            String alarmTypeName = "明火识别";
            //报警内容
            String content = "火焰识别";
            //图片
            String url = "http://192.168.10.206:6881/prod-api/profile/snap/"+remark.substring(0,7)+"/"+serialNumber+"_"+serialNumber+"_"+remark+".jpg";
            //String picUrl = "http://58.56.125.18:6881/prod-api/profile/snap/202412/37010200001320000003_37010200001320000003_2024-12-18T13:53:06.jpg";
            String picUrl = PictureDownload.downloadPicture(url);
            boolean insertAlarmFlag = false;
            //查询这个设备号这种类型的报警上次报警时间，如果时间间隔在2小时以内，不报警
            List<AlarmRecord> alarmList = alarmRecordMapper.selectList(new QueryWrapper<AlarmRecord>().eq("number", serialNumber).eq("type", alarmTypeName));
            if (alarmList.isEmpty()) {//没有记录时添加
                AlarmRecord alarmRecord = new AlarmRecord();
                alarmRecord.setNumber(serialNumber);
                alarmRecord.setTime(DateUtil.now());
                alarmRecord.setType(alarmTypeName);
                alarmRecordMapper.insert(alarmRecord);
                insertAlarmFlag = true;
            } else {//有记录时判断加修改
                AlarmRecord alarmRecord = alarmList.get(0);
                String times = alarmRecord.getTime();
                boolean timeFlag = DateUtils.judgmentDate(times,0.5);
                if (timeFlag) {
                    alarmRecord.setTime(DateUtil.now());
                    alarmRecordMapper.update(alarmRecord, new QueryWrapper<AlarmRecord>().eq("number", serialNumber).eq("type", alarmTypeName));
                    insertAlarmFlag = true;
                }
            }
            if (insertAlarmFlag){
                jsonParamN.put("interfaceType", "1");
                jsonParamN.put("number", serialNumber);
                jsonParamN.put("content", content);
                jsonParamN.put("alarmTypeName", alarmTypeName);
                jsonParamN.put("alarmtime", time);
                jsonParamN.put("deviceClassify", 6);
                jsonParamN.put("path", picUrl);
                jsonParamN.put("uuid", UUID.randomUUID().toString());
                restPostOrGet(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo", "POST");
                //异步更新设备状态
                jsonParamN.put("state","2");
                asyncService.updateDeviceCurrentState(jsonParamN);
            }
        }else {
            //异步更新设备状态
            jsonParamN.put("state","1");
            asyncService.updateDeviceCurrentState(jsonParamN);
        }
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 融合永道时间解析
     * @Date Created in 17:03 2023/2/22
     * @Param [str]
     */

    public static String rongHeYongDaoTime(String time){
        String t = "";
        try {
            String[] y = time.split("\\.");
            t = y[0].replace("T"," ");
        }catch (Exception e){
            t = DateUtil.now();
        }
        return t;
    }


    private static void copyInputStreamToFile(InputStream inputStream, File file) throws IOException {
        try (FileOutputStream outputStream = new FileOutputStream(file)) {
            int read;
            byte[] bytes = new byte[1024];
            while ((read = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, read);
            }
        }
    }
}
